package log

import (
	"fmt"

	"github.com/go-kratos/kratos/v2/log"

	ylog "gitee.com/shuokeyun/common/log"
	"gitee.com/shuokeyun/kratos/conf"
)

// Logger .
type Logger struct {
	log ylog.Logger
}

// NewLogger .
func NewLogger(c *conf.Logging) *Logger {
	l, err := ylog.ParseLevel(c.GetLevel())
	if err != nil {
		panic(err)
	}
	return &Logger{
		log: ylog.NewLogger(
			ylog.WithOut(c.GetOut()),
			ylog.WithLogDir(c.GetDir()),
			ylog.WithLevel(l),
			ylog.WithMaxAge(int(c.GetMaxAge())),
			ylog.WithRotationSize(int(c.GetRotationSize())),
			ylog.WithCallerSkip(-1),
		),
	}
}

// Log .
func (l *Logger) Log(level log.Level, kv ...interface{}) error {
	if len(kv) == 0 || len(kv)%2 != 0 {
		l.log.Warnf("Keyvalues must appear in pairs: %v", kv)
		return nil
	}
	data := make(map[string]interface{})
	for i := 0; i < len(kv); i += 2 {
		data[fmt.Sprint(kv[i])] = fmt.Sprint(kv[i+1])
	}
	msg, ok := data["msg"]
	if ok {
		delete(data, "msg")
	}
	var message string
	if msg != nil {
		message = fmt.Sprint(msg)
	}
	switch level {
	case log.LevelDebug:
		l.log.Logw(ylog.LevelDebug, message, data)
	case log.LevelInfo:
		l.log.Logw(ylog.LevelInfo, message, data)
	case log.LevelWarn:
		l.log.Logw(ylog.LevelWarn, message, data)
	case log.LevelError:
		l.log.Logw(ylog.LevelError, message, data)
	case log.LevelFatal:
		l.log.Logw(ylog.LevelFatal, message, data)
	}
	return nil
}
